package mdm.com.sap.Ftp;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


import mdm.com.sap.SapUtil;

public class FtpUtil {

    public FTPClient ftp;

    public List<String> arFiles;

    /**
     * 重载构造函数
     * 
     * @param isPrintCommmand
     *            是否打印与FTPServer的交互命令
     */
    public FtpUtil(boolean isPrintCommmand) {
        ftp = new FTPClient();
        arFiles = new ArrayList<String>();
        if (isPrintCommmand) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        }
    }

    /**
     * 登陆FTP服务器
     * 
     * @param host
     *            FTPServer IP地址
     * @param port
     *            FTPServer 端口
     * @param username
     *            FTPServer 登陆用户名
     * @param password
     *            FTPServer 登陆密码
     * @return 是否登录成功
     * @throws IOException
     */
    public boolean login(String host, int port, String username, String password) {
        try {
            this.ftp.connect(host, port);
            if (FTPReply.isPositiveCompletion(this.ftp.getReplyCode())) {
                if (this.ftp.login(username, password)) {
                    this.ftp.setControlEncoding("GBK");
                    return true;
                }
            }
            if (this.ftp.isConnected()) {
                this.ftp.disconnect();
            }
        } catch (SocketException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    /**
     * 关闭数据链接
     * 
     * @throws IOException
     */
    public void disConnection() throws IOException {
        if (this.ftp.isConnected()) {
            this.ftp.disconnect();
        }
    }
    /**
     * 删除文件
     * @param path  文件所在路径
     * @param fileName  文件名称
     * @return
     * @throws IOException
     */
//    public boolean deleteFile(String path,String fileName) throws IOException {
//        ftp.changeWorkingDirectory(new String(path.getBytes("GBK"),"ISO-8859-1"));
//       return  ftp.deleteFile(fileName);
//    }

    /**
     * 向FTP 写入文件
     * 
     * @param path
     *            路劲
     * @param list
     *            文件内容
     * @return
     * @throws IOException 
     */
    public void uploadFile(String path, List<String> list) throws IOException {
        InputStream is = null;
        StringBuffer buf = new StringBuffer();
        for (String str : list) {
            buf = buf.append(str);
            // 行与行之间的分隔符 相当于“\n”
            buf = buf.append(System.getProperty("line.separator"));
        }
        // 1.输入流
        is = new ByteArrayInputStream(buf.toString().getBytes());
        ftp.changeWorkingDirectory(new String(path.getBytes("GBK"),"ISO-8859-1"));
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        String fileName=SapUtil.formatToTIME()+".TXT";
        ftp.storeFile(fileName, is);
        is.close();
    }
    
    /**
     * 读取FTP文件内容
     * @param path   目录路径
     * @param fileName  文件名称
     * @throws IOException
     */
    public List<String> readFile(String path,String fileName) throws IOException {
        List<String> list = new ArrayList<String>();
        ftp.changeWorkingDirectory(new String(path.getBytes("GBK"),"ISO-8859-1"));
      //5.遍历下载的目录  
//        FTPFile[] fs = ftp.listFiles();  
//        for (FTPFile ff : fs) { 
//            byte[] bytes=ff.getName().getBytes("iso-8859-1");  
//            String fn=new String(bytes,"utf8");
//            if(fn.toLowerCase().equals(fileName.toLowerCase())) {
//                list = FtpUtil.readTxt(ftp.retrieveFileStream(ff.getName()));
//            }
//        }
        list = FtpUtil.readTxt(ftp.retrieveFileStream(new String(fileName.getBytes("GBK"),"ISO-8859-1")));
        return list;
    }
    
    
    public static List<String> readTxt(InputStream in){
        List<String> list = new ArrayList<String>();
        if (null != in) { 
            try {
                Reader reader = new InputStreamReader(in, "UTF-8");
                BufferedReader br = new BufferedReader(reader);
                String tempString = null;
                // 一次读入一行，直到读入null为文件结束
                while ((tempString = br.readLine()) != null) {
                    list.add(tempString);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 递归遍历出目录下面所有文件
     * 
     * @param pathName
     *            需要遍历的目录，必须以"/"开始和结束
     * @throws IOException
     */
    public List<String> List(String pathName) throws IOException {
        List<String> list = new ArrayList<String>();
        System.out.println(pathName);
        if (pathName.startsWith("/") && pathName.endsWith("/")) {
            String directory = pathName;
            // 更换目录到当前目录
            this.ftp.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"));
            FTPFile[] files = this.ftp.listFiles();
            for (FTPFile file : files) {
                if (file.isDirectory()) {
                    if (!file.getName().equals(".")) {
                        if (!file.getName().equals("..")) {
                            list.add(file.getName());
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 递归遍历目录下面指定的文件名
     * 
     * @param pathName
     *            需要遍历的目录，必须以"/"开始和结束
     * @param ext
     *            文件的扩展名
     * @throws IOException
     */
    public List<String> List(String pathName, String ext) throws IOException {
        List<String> list = new ArrayList<String>();
        if (pathName.startsWith("/") && pathName.endsWith("/")) {
            String directory = pathName;
            // 更换目录到当前目录
            ftp.changeWorkingDirectory(new String(directory.getBytes("GBK"),"ISO-8859-1"));
            FTPFile[] files = this.ftp.listFiles();
            for (FTPFile file : files) {
                if (file.isFile()) {
                    if (file.getName().toLowerCase().endsWith(ext)) {
                        list.add(file.getName());
                    }
                }
            }
        }
        return list;
    }
    
    

}
